package com.smartinput.config

import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.CorsConfigurationSource
import org.springframework.web.cors.UrlBasedCorsConfigurationSource

@Configuration
class CorsConfig {
    
    @Value("\${app.cors.allowed-origins}")
    private lateinit var allowedOrigins: String
    
    @Value("\${app.cors.allowed-methods}")
    private lateinit var allowedMethods: String
    
    @Value("\${app.cors.allowed-headers}")
    private lateinit var allowedHeaders: String
    
    @Bean
    fun corsConfigurationSource(): CorsConfigurationSource {
        val configuration = CorsConfiguration()
        
        // 设置允许的源 - 使用allowedOriginPatterns避免精确匹配问题
        val origins = allowedOrigins.split(",").map { it.trim() }
        configuration.allowedOriginPatterns = origins.toMutableList()
        
        // 设置允许的方法
        val methods = allowedMethods.split(",").map { it.trim() }
        configuration.allowedMethods = methods
        
        // 设置允许的头部
        val headers = allowedHeaders.split(",").map { it.trim() }
        configuration.allowedHeaders = headers
        
        // 允许凭据
        configuration.allowCredentials = true
        
        // 设置预检请求的缓存时间
        configuration.maxAge = 3600
        
        val source = UrlBasedCorsConfigurationSource()
        source.registerCorsConfiguration("/**", configuration)
        return source
    }
}
